package org.example;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/customer-service")
@CrossOrigin(origins = "*")
public class CustomerServiceController {

    private final ChatClient chatClient;
    private final KnowledgeBaseService knowledgeBaseService;
    private final ConversationContextService conversationContextService;
    private final FeedbackService feedbackService;
    private final QuestionCacheService questionCacheService;

    @Autowired
    public CustomerServiceController(ChatClient.Builder chatClientBuilder,
                                   KnowledgeBaseService knowledgeBaseService,
                                   ConversationContextService conversationContextService,
                                   FeedbackService feedbackService,
                                   QuestionCacheService questionCacheService) {
        this.chatClient = chatClientBuilder.build();
        this.knowledgeBaseService = knowledgeBaseService;
        this.conversationContextService = conversationContextService;
        this.feedbackService = feedbackService;
        this.questionCacheService = questionCacheService;
    }

    @RateLimiter(name = "apiRateLimiter")
    @PostMapping("/ask")
    public Map<String, Object> askQuestion(@RequestBody Map<String, String> request) {
        String question = request.get("question");
        String conversationId = request.get("conversationId");
        
        // 首先检查缓存
        String cachedAnswer = questionCacheService.get(question);
        if (cachedAnswer != null) {
            return Map.of(
                "answer", cachedAnswer,
                "conversationId", conversationId != null ? conversationId : "",
                "averageRating", feedbackService.getAverageRating()
            );
        }
        
        // 然后查询知识库
        String knowledgeAnswer = knowledgeBaseService.queryKnowledgeBase(question);
        if (knowledgeAnswer != null) {
            questionCacheService.put(question, knowledgeAnswer);
            return Map.of(
                "answer", knowledgeAnswer,
                "conversationId", conversationId != null ? conversationId : "",
                "averageRating", feedbackService.getAverageRating()
            );
        }

        // 如果是新会话，创建会话ID
        if (conversationId == null || conversationId.isEmpty()) {
            conversationId = conversationContextService.createNewConversation();
        }

        // 获取历史上下文
        String context = conversationContextService.getContext(conversationId);
        
        // 构建包含上下文的提示词
        String prompt = """
                你是一个专业的客服代表，请以友好、专业的态度回答客户问题。
                以下是之前的对话历史：
                %s
                
                请根据以下客户问题提供准确、简洁的回答：
                问题：%s
                """.formatted(context, question);

        // 获取AI回答
        String answer = chatClient.prompt()
                .user(prompt)
                .call()
                .content();

        // 更新会话上下文
        String newContext = context + "\n用户: " + question + "\n客服: " + answer + "\n";
        conversationContextService.updateContext(conversationId, newContext);

        // 缓存回答
        questionCacheService.put(question, answer);

        return Map.of(
            "answer", answer,
            "conversationId", conversationId,
            "averageRating", feedbackService.getAverageRating()
        );
    }

    @RateLimiter(name = "apiRateLimiter")
    @PostMapping("/feedback")
    public Map<String, Object> submitFeedback(@RequestBody Feedback feedback) {
        feedbackService.saveFeedback(feedback.getConversationId(), feedback.getRating());
        return Map.of(
            "status", "success",
            "conversationId", feedback.getConversationId(),
            "averageRating", feedbackService.getAverageRating()
        );
    }

    @GetMapping("/suggestions")
    public List<String> getSuggestions(@RequestParam String query) {
        // 常见问题列表，可以从数据库或配置文件中加载
        List<String> commonQuestions = List.of(
            "如何退货？",
            "营业时间是什么时候？",
            "运费是多少？",
            "支持哪些支付方式？",
            "会员有什么优惠？"
        );

        // 过滤匹配的问题
        return commonQuestions.stream()
                .filter(q -> q.toLowerCase().contains(query.toLowerCase()))
                .collect(Collectors.toList());
    }
}